import socket
import sys

class MessageSubscriber:
    def __init__(self, host='127.0.0.1', port=8888):
        """初始化消息订阅器"""
        self.host = host
        self.port = port
        # 创建UDP套接字
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        # 绑定地址和端口
        try:
            self.socket.bind((self.host, self.port))
            print(f"订阅器启动，正在监听 {self.host}:{self.port}")
        except socket.error as e:
            print(f"绑定失败: {e}")
            sys.exit(1)
    
    def parse_message(self, data):
        """解析接收到的消息"""
        try:
            parts = data.split('|', 1)
            if len(parts) != 2:
                print("消息格式错误")
                return None, None
            
            float_value = float(parts[0])
            string_value = parts[1]
            return float_value, string_value
        except ValueError:
            print("无法解析浮点数值")
            return None, None
    
    def subscribe(self):
        """开始接收消息"""
        while True:
            try:
                # 接收数据，最大缓冲区1024字节
                data, addr = self.socket.recvfrom(1024)
                data = data.decode('utf-8')
                print(f"\n收到来自 {addr} 的消息: {data}")
                
                float_val, string_val = self.parse_message(data)
                if float_val is not None:
                    print(f"浮点数值: {float_val}")
                    print(f"字符串值: {string_val}")
            except KeyboardInterrupt:
                print("\n订阅器停止")
                break
            except Exception as e:
                print(f"接收消息时出错: {e}")
    
    def close(self):
        """关闭套接字"""
        self.socket.close()

if __name__ == "__main__":
    subscriber = MessageSubscriber()
    try:
        subscriber.subscribe()
    except KeyboardInterrupt:
        print("\n用户中断，正在退出...")
    finally:
        subscriber.close()
